var exports = {
    createTag: function() {
        chrome.tabs.executeScript({
            code: 'Webtags.showDialog()'
        });
    },
    markPage: function(text) {
        chrome.tabs.executeScript({
            code: 'Webtags.saveTag(' + JSON.stringify(text) + ')'
        });
    },
    clearTags: function() {
        chrome.tabs.executeScript({
            code: 'Webtags.clearTags()'
        });
    },
    clearAllTags: function() {
        chrome.storage.local.clear();
    },
    toggleTags: function() {
        chrome.tabs.executeScript({
            code: 'Webtags.toggleTags()'
        });
    },
    showHighlighter: function() {
        chrome.tabs.executeScript({
            code: 'Webtags.showHighlighter()'
        });
    }
};

function onContextMenu(info) {
    switch (info.menuItemId) {
        case 'create':
            exports.createTag();
            break;
        case 'highlight':
            exports.showHighlighter();
            break;
        case 'mark':
            exports.markPage(info.selectionText);
            break;
        case 'toggle':
            exports.toggleTags();
            break;
        case 'clear':
            exports.clearTags();
            break;
        case 'clearall':
            exports.clearAllTags();
            break;
    }
}

function onCommand(command) {
    onContextMenu({menuItemId: command});
}

function onMessage(request, sender, response) {
    if (request === 'add-components')
        chrome.tabs.executeScript(sender.tab.id, { file: 'main.js' });
}

function onStorage(changes, area) {
    var added = {}, removed = [];
    for (var k in changes) {
        if (changes[k].newValue != null)
            added[k] = changes[k].newValue;
        else
            removed.push(k);
    }
    var storage = area === 'sync' ? chrome.storage.local : chrome.storage.sync;
    if (Object.keys(added).length)
        storage.set(added, checkLastError);
    if (removed.length)
        storage.remove(removed, checkLastError);
}

function onInstalled(details) {
    if (details.reason === 'install') {
        chrome.tabs.query({url: '*://*/*'}, function(t) {
            var x = { file: 'setup.js' };
            for (var i = 0; i < t.length; i++)
                chrome.tabs.executeScript(t[i].id, x);
        });
    }
    loadContextMenu();
}

function loadContextMenu() {
    chrome.contextMenus.create({
        id: 'create',
        title: 'Create tag here',
        documentUrlPatterns: ['*://*/*']
    });
    chrome.contextMenus.create({
        id: 'highlight',
        title: 'Highlight this page',
        documentUrlPatterns: ['*://*/*']
    });
    chrome.contextMenus.create({
        id: 'clear',
        title: 'Clear this page',
        documentUrlPatterns: ['*://*/*']
    });
    chrome.contextMenus.create({
        id: 'separator',
        type: 'separator',
        documentUrlPatterns: ['*://*/*']
    });
    chrome.contextMenus.create({
        id: 'clearall',
        title: 'Clear all tags',
        documentUrlPatterns: ['<all_urls>']
    });
    chrome.contextMenus.create({
        id: 'mark',
        title: "Mark '%s'",
        contexts: ['selection'],
        documentUrlPatterns: ['*://*/*']
    });
}

function checkLastError() {
    if (chrome.runtime.lastError)
        console.warn('[' + getTime() + ']', chrome.runtime.lastError.message);
}

function getTime() {
    var t = new Date();
    return t.getHours() + ':' + t.getMinutes() + ':' +
        ('00' + t.getSeconds()).slice(-2);
}

chrome.runtime.onInstalled.addListener(onInstalled);
chrome.storage.onChanged.addListener(onStorage);
chrome.runtime.onMessage.addListener(onMessage);
chrome.commands.onCommand.addListener(onCommand);
chrome.contextMenus.onClicked.addListener(onContextMenu);
